<?php

namespace App\Service\OpenShop\Import\OpenFull;

use App\Console\Commands\OpenShop\ImportHistoryOrder;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Library\FeiShu\SendFs;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class OpenFullToCollection
{
    public function collection(Collection $collection, ?Command $command)
    {
        $shopCodes = $collection->first()->map(function ($item) {
            return (int)$item[0];
        })->toArray();
        unset($shopCodes[0]);
        $shopCodes = array_values($shopCodes);

        $rmsShops = collect(RmsShopRemote::getShopFieldsByCodes($shopCodes, [
            'id',
            'shopCode',
            'name',
            'shopMobile',
            'address',
            'addressPrefix',
            'province',
            'city',
            'district'
        ])['shopList'])
            ->keyBy('shopCode');

        $rmsShops->pluck('id')->chunk(100)->each(function ($shopIds) use (&$rmsShops) {

            $managerInfos = RmsUserRemote::getShopManagerUserByShopId($shopIds->toArray())['lists'] ?? [];
            if (!$managerInfos) {
                return;
            }

            $rmsShops = $rmsShops->map(function ($item) use ($managerInfos) {
                foreach ($managerInfos as $v) {
                    if ($v['shopId'] == $item['id']) {
                        $item['merchantInfo'] = $v;
                        break;
                    }
                }

                return $item;
            });
        });

        $params = $collection
            ->first()
            ->map(function ($item, $row) use ($rmsShops) {

                // 标题
                if ($row == 0) {
                    return null;
                }

                $row      = $row + 1;
                $shopCode = (int)$item[0];
                $rmsShop  = $rmsShops[$shopCode] ?? [];

                // 参数校验
                $param = (new OpenFullParam())->init($item->toArray(), $row, $rmsShop)->prepareParam();
                if ($param->getErrMsg()) {

                    // 准备数据异常
                    ImportHistoryOrder::$errOrders .= $param->getErrMsg() . PHP_EOL;
                    dump($param->getErrMsg());
                    return null;
                }

                // 提醒数据
                if ($param->getNoticeMsg()) {
                    ImportHistoryOrder::$noticeOrders .= $param->getNoticeMsg() . "；仅提示，可强制执行" . PHP_EOL;
                    dump($param->getNoticeMsg());
                }

                return $param;
            });

        if ((ImportHistoryOrder::$errOrders || ImportHistoryOrder::$noticeOrders) && $command) {
            $command->warn('===========================' . PHP_EOL);
            $command->warn('信息校验存在以下问题：' . PHP_EOL);
            $command->warn(ImportHistoryOrder::$errOrders);
            $command->warn(ImportHistoryOrder::$noticeOrders);
            $command->info("===========================");
            $yn = $command->ask("确认要继续导入吗？(y/n) y");
            $yn = strtolower($yn);
            if ($yn == 'n') {
                $command->info('退出...');
                return;
            }

            $yn = $command->ask("再次确认，确认要继续导入吗？(y/n) y");
            if ($yn == 'n') {
                $command->info('退出...');
                return;
            }
        }

        $params->filter()
               ->each(function ($param, $row) {

                   $row = $row + 1;
                   dump("第{$row}行开始执行.............");

                   // 跑流程
                   try {
                       (new OpenFullExecute($param))->execute();
                       ImportHistoryOrder::$successOrders .= "第{$row}行，门店编号：" . $param->shopCode . ':' . "正常执行完成" . PHP_EOL;
                   } catch (CustomHttpResponseException $e) {
                       ImportHistoryOrder::$errOrders .= "第{$row}行，门店编号：" . $param->shopCode . ':' . ($e->getResponse()->original['msg'] ?? '') . PHP_EOL;
                   } catch (\Exception $e) {
                       ImportHistoryOrder::$errOrders .= "第{$row}行，门店编号：" . $param->shopCode . ':' . $e->getMessage() . PHP_EOL;
                   }
               });

        $content = '';
        if (ImportHistoryOrder::$successOrders) {
            $content .= "========Success:========" . PHP_EOL;
            $content .= ImportHistoryOrder::$successOrders;
        }

        if (ImportHistoryOrder::$errOrders) {
            $content .= "========Error:========" . PHP_EOL;
            $content .= ImportHistoryOrder::$errOrders;
        }

        dump($content);

        if ($command) {
            $sendFs = SendFs::newRobot(SendFs::ROBOT_OPEN_SHOP)->setTitleContent("导入历史开店订单执行结果", $content);

            if (config('app.env') == 'prod' || config('app.env') == 'pre') {
                $sendFs = $sendFs->setAtUid('5dd87136'); // 山治
                $sendFs = $sendFs->setAtUid('9efgbcdb'); // 吉连
            } else {
                $sendFs = $sendFs->setAtUid('9efgbcdb'); // 吉连
            }

            $sendFs->send();
        }
    }
}
